const pendingAnimations = new Set();

export default function highlightElement(el: HTMLElement) {
  // the parent element must be positioned
  const scrollParent = el.offsetParent;
  if (!scrollParent) {
    return;
  }
  const prect = scrollParent.getBoundingClientRect();
  const rect = el.getBoundingClientRect();
  if (rect.bottom > prect.bottom || rect.top < prect.top) {
    el.scrollIntoView({
      behavior: "instant",
      block: "center",
      inline: "center",
    });
  }
  const animations = el.getAnimations();
  animations.forEach((a) => {
    if (pendingAnimations.has(a.id)) {
      a.cancel();
    }
  });
  const ani = el.animate(
    [
      {
        backgroundColor: "rgb(233, 85, 19)",
      },
      {
        backgroundColor: "transparent",
      },
    ],
    { duration: 1000 },
  );
  ani.oncancel = function () {
    pendingAnimations.delete(ani.id);
  };
  ani.onfinish = function () {
    pendingAnimations.delete(ani.id);
  };
  pendingAnimations.add(ani.id);
}
